# encoding: utf-8
""" 
@version: v1.0 
@author: autumner 
@license: Apache Licence  
@contact: 18322313385@163.com 
@site:  https://gitee.com/autumner/pythoncookbook
@software: PyCharm 
@file: shell_out_shell.py 
@time: 2019/8/1 上午10:03
@note:
调用外部命令
"""
import subprocess

out_bytes = subprocess.check_output(['ss', '-t', '-l'])
# print(out_bytes)
'以文本形式返回需要解码'
out_text = out_bytes.decode('utf-8')
print(out_text)

'捕捉异常，获取返回码, 设置超时'
try:
    out_bytes = subprocess.check_output(['ss', '-tl', '-p'], timeout=5)
    print(out_bytes.decode('utf-8'))
except subprocess.CalledProcessError as e:
    out_bytes = e.output
    code = e.returncode

'直接调用shell，可以操作更复杂shell命令'
out_bytes = subprocess.check_output('ss -a | grep https', shell=True)
print(out_bytes.decode('utf-8'))

'对子进程进行交互操作，需要用到Popen'
text = b'hello world' \
       b'this is a test' \
       b'good bye!'

p = subprocess.Popen(['wc'],
                     stdout = subprocess.PIPE,
                     stdin = subprocess.PIPE)

stdout, stderr = p.communicate(text)

out = stdout.decode('utf-8')
print('输出对text文本内容统计数')
print(out, stderr)